;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; This file is part of ICCLE2.
;
; ICCLE2 is free software: you can redistribute it and/or modify
; it under the terms of the GNU General Public License as published by
; the Free Software Foundation, either version 3 of the License, or
; (at your option) any later version.
;
; ICCLE2 is distributed in the hope that it will be useful,
; but WITHOUT ANY WARRANTY; without even the implied warranty of
; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
; GNU General Public License for more details.
;
; You should have received a copy of the GNU General Public License
; along with ICCLE2.  If not, see <http://www.gnu.org/licenses/>.
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(defun folds (l0 nfolds)
  (let (folds
        (i nfolds)
        (l (sort-ish l0)))
    (dotimes (j nfolds)
      (push (make-fold :index j) folds)) ; initialize the folds
    (if (= nfolds 1)
        (dolist (x l)
          (push x (fold-test  (nth 0 folds)))
          (push x (fold-train (nth 0 folds))))
        (dolist (x l)
          (decf  i) ; go to the next fold
          (dotimes (j nfolds)
            (if (= i j) 
                (push x (fold-test  (nth j folds)))  ; add 1/j to "test"
                (push x (fold-train (nth j folds))))) ; add rest to "train"
          (if (zerop i)
              (setf i nfolds))))
    folds)) ; go back to the start

(defun sort-ish (l)
   (sort (copy-list l) #'last1<~))

(defun last1<~ (x y)
  (<~ (last1 x) (last1 y)))

